package evolution.problem;

public class MinimizationFitnessFunction implements FitnessFunction {

	public static final double BEST = Integer.MAX_VALUE;

	private AbstractMinimizationProblem optimizationProblem;

	public MinimizationFitnessFunction(
			AbstractMinimizationProblem optimizationProblem) {
		this.optimizationProblem = optimizationProblem;
	}

	@Override
	public double getValue(double[] chromosome) {
		double realVal = optimizationProblem.getValue(chromosome);
		double globalMinimumValue = optimizationProblem.getOptimumValue();

		if (globalMinimumValue < 0) {
			realVal -= globalMinimumValue;
		}
		
		if (realVal != 0) {
			return 1 / realVal;
		}

		return BEST;
	}

	public double convertToRealValue(double fitnessValue) {
		if (fitnessValue == BEST) {
			return optimizationProblem.getOptimumValue();
		}

		double realVal = 1 / fitnessValue;

		double globalMinimumValue = optimizationProblem.getOptimumValue();
		if (globalMinimumValue < 0) {
			realVal += globalMinimumValue;
		}

		return realVal;
	}
}
